package com.jgp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jgp.common.R;
import com.jgp.entity.User;
import com.jgp.service.UserService;
import com.jgp.utils.SMSUtils;
import com.jgp.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession) {
        String phone = user.getPhone();
        if (Strings.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);
//        使用阿里云提供的短信服务发送短信
//            SMSUtils.sendMessage("瑞吉外卖", "", phone, code);
//            验证码存起来
            httpSession.setAttribute(phone, code);
            return R.success("成功");
        }
        return R.error("失败");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession httpSession){
//        获取手机号
        String phone = map.get("phone").toString();

//        获取验证码
        String code = map.get("code").toString();

//从session获取保存的验证码
        Object attribute = httpSession.getAttribute(phone);

//        进行验证码的比对
        if(attribute!=null&&attribute.equals(code)){
//        如果比对成功，则成功

//        判断手机号用户是否为新用户，如果是新用户则自动注册
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(userLambdaQueryWrapper);
            if(user==null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);

            }
            httpSession.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登陆失败");
    }
}


